package com.wuseguang.springcloud.Classcardservice.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.JdbcTemplate.ClassCardDao;
import com.wuseguang.springcloud.util.StringUtil;
import com.wuseguang.springcloud.util.TaskCpstableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class ClassCardServiceImpl implements ClassCardService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ClassCardDao classCardDao;

    //private TaskCpstableUtils taskCpstableUtils = new TaskCpstableUtils();

    //推送任务的线程池
    //private static ThreadPoolExecutor executer = new ThreadPoolExecutor(10, 20, 1200, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    /**
     * @描述 推送接口
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void pushClassCard(String id) {
        logger.info("ClassCardServiceImpl-->pushClassCard-->id={}", id);
        if (id == null || "".equals(id)) {
            return;
        }
        String sql = "SELECT GROUP_CONCAT(NAME ) as string FROM heartbeatfield";
        String s = classCardDao.queryString(sql);
        if ("".equals(s)) {
            s = "*";
        }
        logger.info("pushClassCarde()-->pushClassCard={}", s);
        String sql1 = "SELECT " + s + " FROM  bancard WHERE id in(" + id + ")";
        List<Map<String, Object>> maps = null;
        try {
            maps = classCardDao.queryListMap(sql1);
        } catch (Exception e) {
            logger.info("e={}", e);
        }
        if (maps != null && maps.size() > 0) {
            logger.info("pushClassCard-->maps.toString()={}", maps.toString());
            //taskCpstableUtils.setMaps(maps);
            //executer.execute(taskCpstableUtils);
            try {
                sql = "insert into `pushlog` (`deviceid`, `clientid`, `content`, `result`, `time`) values(?,?,?,?,now())";
                String sqld = "update bancard set pstatus=1 where deviceid=?";
                for (int i = 0; i < maps.size(); i++) {
                    Map<String, Object> stringObjectMap = maps.get(i);
                    Object deviceid = stringObjectMap.get("deviceid");
                    stringObjectMap.remove("deviceid");
                    String clientid = TaskCpstableUtils.sendandroid((String) stringObjectMap.get("clientid"), stringObjectMap.toString());
                    classCardDao.updateByParameter(sql, deviceid, stringObjectMap.get("clientid"), stringObjectMap.toString(), clientid);
                    if (clientid != null && clientid.contains("successed_offline")) {
                        classCardDao.updateByParameter(sqld, deviceid);
                    }
                }
            } catch (Exception e) {
                logger.info("pushClassCard-->error={}", e);
            }
            logger.info("pushClassCard-->推送执行完毕.....");
        }
        logger.info("pushClassCard-->执行完毕.....");
    }

    private String iterList(List<Integer> list) {
        logger.info("iterList==>list={}", list.toString());
        if (list == null || list.size() <= 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            stringBuilder.append(list.get(i)).append(",");
        }
        String substring = stringBuilder.substring(0, stringBuilder.length() - 1);
        logger.info("iterList==>substring={}", substring);
        return substring;
    }

    private String iterStringList(List<String> list) {
        logger.info("iterStringList==>list={}", list.toString());
        if (list == null || list.size() <= 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            stringBuilder.append(list.get(i)).append(",");
        }
        String substring = stringBuilder.substring(0, stringBuilder.length() - 1);
        logger.info("iterStringList==>substring={}", substring);
        return substring;
    }


    public static void main(String[] args) {
        boolean successed_offline = "{result=ok, taskId=OSS-0917_4eab4fdb8f34a1d3f2ef48ecbe67dc5f, status=successed_offline}".contains("successed_offline");
        System.out.println(successed_offline);
    }

    /**
     * @描述 单个班级，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void classesAndCards(String classid) {
        if (classid == null || "".equals(classid)) {
            return;
        }
        String sql = "SELECT GROUP_CONCAT(b.id) as string FROM classroom r,classes s ,bancard b WHERE r.classid=s.id AND b.classroomid=r.id AND r.classid in (" + classid + ")";
        String s = classCardDao.queryString(sql);
        pushClassCard(s);
    }

    @Override
    public void classesAndCards(Integer classid) {
        if (classid == null || "".equals(classid)) {
            return;
        }
        String sql = "SELECT GROUP_CONCAT(b.id) as string FROM classroom r,classes s ,bancard b WHERE r.classid=s.id AND b.classroomid=r.id AND r.classid=?";
        String s = classCardDao.queryString(sql, classid);
        pushClassCard(s);
    }

    /**
     * @描述 多个班级，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void classesAndCards(List<Integer> classids) {
        String s = iterList(classids);
        if (s == null) {
            return;
        }
        String sql = "SELECT GROUP_CONCAT(b.id) as string FROM classroom r,classes s ,bancard b WHERE r.classid=s.id AND b.classroomid=r.id AND r.classid in (" + s + ")";
        String s1 = classCardDao.queryString(sql);
        pushClassCard(s1);
    }

    /**
     * @描述 单个教室，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void classRoomAndCards(String classRoomid) {
        if (classRoomid == null || "".equals(classRoomid)) {
            return;
        }
        String sql = "SELECT GROUP_CONCAT(b.id) as string FROM classroom r,bancard b WHERE  b.classroomid=r.id AND r.id=?";
        String s1 = classCardDao.queryString(sql, classRoomid);
        pushClassCard(s1);
    }

    /**
     * @描述 多个教室，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void classRoomAndCards(List<Integer> classRoomids) {
        String s = iterList(classRoomids);
        if (s == null) {
            return;
        }
        String sql = "SELECT GROUP_CONCAT(b.id) as string FROM classroom r,bancard b WHERE  b.classroomid=r.id AND r.id in (" + s + ")";
        String s1 = classCardDao.queryString(sql);
        pushClassCard(s1);
    }

    /**
     * @描述 单个设备id，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void bancardAndCards(String bancardid) {
        pushClassCard(bancardid);
    }

    /**
     * @描述 多个设备ids，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void bancardAndCards(List<Integer> bancardids) {
        String s = iterList(bancardids);
        if (s == null) {
            return;
        }
        pushClassCard(s);
    }

    /**
     * @描述 单个设备，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void deviceidAndCards(String deviceid) {
        String sql = "SELECT GROUP_CONCAT(b.id) as string FROM classroom r,bancard b WHERE b.classroomid=r.id AND b.deviceid=?";
        String s1 = classCardDao.queryString(sql, deviceid);
        pushClassCard(s1);
    }

    /**
     * @描述 多个设备，推送
     * @创建人 zm
     * @创建时间 2020/1/16
     */
    @Override
    public void deviceidAndCards(List<String> deviceids) {
        String s = iterStringList(deviceids);
        if (s == null) {
            return;
        }
        String sql = "SELECT GROUP_CONCAT(b.id) as string FROM classroom r,bancard b WHERE b.classroomid=r.id AND b.deviceid in (" + StringUtil.spilt(s) + ")";
        String s1 = classCardDao.queryString(sql);
        pushClassCard(s1);
    }
}
